import time
import math
import random
import datetime

_today = datetime.date.today()
today_time = int(time.mktime(_today.timetuple()))
DAY = 60 * 60 * 24


def now():
    return int(time.time() * 1000)


def _add_month_interval(dt, inter):
    m = dt.month + inter - 1
    y = dt.year + math.floor(m / 12)
    m = m % 12 + 1
    return y, m


def add_month_interval(dt, inter):
    y, m = _add_month_interval(dt, inter)
    y2, m2 = _add_month_interval(dt, inter + 1)
    max_d = (datetime.date(y2, m2, 1) - datetime.timedelta(days=1)).day
    d = dt.day <= max_d and dt.day or max_d
    return datetime.date(y, m, d)


def add_year_interval(dt, inter):
    return add_month_interval(dt, inter * 12)


def make_date(days=1):
    start = today_time - days * DAY
    end = start + DAY - 1
    three_date = add_month_interval(_today, -3)
    _three_time = int(time.mktime(three_date.timetuple()))
    three_time = _three_time - days * DAY + random.randint(10, 50)
    return {'create_time_range': {'start_time': three_time},
            'time_range': {'start_time': start, 'last_time': end}
            }
